<template>
  <div class="chat" @click="closeDelButton()">
    <!-- 个人信息 -->
    <!-- <div class="my-info">
      <img
        class="not-avatar"
        title="消息"
        v-if="isChat"
        @click="leftShow(1)"
        src="./png/message.png"
        alt=""
      />
    </div> -->
    <!-- 右侧对话列表 -->
    <div class="chat-container">
      <div class="chat-list">
        <div class="chat-title">
          <span v-html="this.chatTitle" />
          <i
            style="float: right"
            class="el-icon-setting"
            @click="setGroupBtn"
            v-if="fixedFlag === 1 && reduceFlag === 0"
          />
        </div>
        <ul>
          <li v-if="moreMessageBtnShow && chatList.length !== 0" class="more-message-btn">
            <el-button @click="getMoreMessage" type="text">查看更多消息
            </el-button>
          </li>
          <li :id="'infoId-' + item.infoId" class="chat-item" v-for="(item, index) in chatList" :key="item.infoId">
            <div class="myself" v-if="item.sendUserId === nowUserId && item.msgFlag === 0">
              <div>
                <p>{{ item.sendUserName }} <span> {{ item.sendTime }} </span> </p>
                <div @mouseleave="item.show = false" @contextmenu.prevent="revokeBtnShowFn(item)">
                  <!-- 文本信息 -->
                  <p class="msg-wrapper" v-html="item.msg"></p>
                  <!-- 是否已读 -->
                  <p class="read-or-not" v-if="!fixedFlag">
                    {{ item.unreadFlag ? "已读" : "未读" }}
                  </p>
                  <div class="withdraw-wrapper" v-if="item.show">
                    <el-button link type="primary" @click="revokeBtn(item, index)">撤回</el-button>
                  </div>
                </div>
              </div>
              <div><span> {{ item.sendUserName.substr(0, 1) }} </span></div>
            </div>

            <div class="others" v-if="item.sendUserId !== nowUserId && item.msgFlag === 0">
              <div><span> {{ item.sendUserName.substr(0, 1) }} </span></div>
              <div>
                <p>
                  {{ item.sendUserName }} <span> {{ item.sendTime }} </span>
                </p>
                <!-- 文本信息 -->
                <p class="msg-wrapper" v-html="item.msg"></p>
              </div>
            </div>

            <div style="text-align: center; color: #8896b7; font-size: 14px" v-if="item.msgFlag === 1">
              <span v-html="item.msg"></span>
            </div>
          </li>
          <li ref="lastChatItemRef" class="last-chat-item"></li>
        </ul>
      </div>

      <!-- 消息发送框 -->
      <div class="chat-send" v-if="chatTitle">
        <!-- 工具栏 -->
        <div :class="['chat-tool']">
          <div>
            <Emoji @sendEmoji="sendEmoji" />
          </div>
        </div>

        <!-- 消息输入框 -->
        <div class="chat-input">
          <el-input
            v-model="sendMessage"
            :rows="3"
            resize="none"
            type="textarea"
            @keyup.enter.native="enterSendBtn"
            maxlength="200"
          />
        </div>

        <!-- 消息发送按钮 -->
        <div class="chat-send-btn">
          <el-button type="primary" @click="sendBtn" size="mini">
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/framework/utils/auth";
import {
  chatGroupQueryApi,
  chatHistoryPageApi,
  chatHistoryListApi,
  chatHistoryDelApi,
  chatHistoryRevokeApi,
  chatGroupInfoApi,
  chatGroupEditApi,
  chatGroupDelApi,
  chatGroupMemberApi,
  chatGroupExitApi,
  chatGroupAddApi,
  getOrgTreeApi,
  getSysUserPageApi,
} from "./chatjs";
// 客服消息
import {
  listAccessInfo,
  getAccessInfo,
  delAccessInfo,
  addAccessInfo,
  updateAccessInfo,
  getAccessInfoApi,
  revokeAccessInfoApi,
  getAccessInfoAllocationApi
} from "../../api/accessInfo/AccessInfo";
import {
  listTouristUser,
  getTouristUser,
  delTouristUser,
  addTouristUser,
  updateTouristUser,
  getTouristInfo
} from "../../api/touristUser/TouristUser";
import { dateFormat } from "@/framework/utils/date";
import Emoji from "./emoji.vue";
import store from "@/store";
import { cloud } from "@/framework/utils/request";
import { getUserTree } from "../../framework/api/notice";

export default {
  name: "chatOnline",

  components: {
    Emoji,
  },
  data() {
    return {
      delUserId: "",
      choseId: "",
      nowChat: false,
      delButton: false,
      nowUserId: "",
      ws: null,
      sendMessage: "",
      lastChatItemRef: null,
      sessionActive: "",
      chatTitle: "客服",
      chatList: [],
      sessionList: {},
      userInfoInPage: null,
      groupId: null,
      moreMessageBtnShow: true,
      // 是否是群组 0不是 1是
      fixedFlag: 0,
      //群组是否已解散或退出 0未解散 1已解散
      reduceFlag: 0,
      drawerVisible: false,
      // 群组成员
      groupInfo: {},
      groupUsers: [],
      adminFlag: false,
      groupForm: {
        groupName: "",
      },
      // 上传文件携带的token
      headers: {
        Authorization: getToken(),
      },
      // 上传文件地址
      uploadUrl:
        process.env.VUE_APP_BASE_API + cloud.file + "/sysFileInfo/upload",
      // 上传的文件，是否是机密文件
      paramsData: {
        secretFlag: "N",
      },
      //------弹窗字段信息-----------------------------
      isChat: true,
      isOrg: true,
      userInfo: {},
      dialogVisible: false,
      treeData: [],
      selectedUserList: [],
      filterText: "",
      treeRef: [],
      ChatRef: "",
      newGroupId: "",
      addMemberGroupId: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      orgTree: [],
      orgTreeRef: [],
      orgFilterText: "",
      orgDefaultProps: {
        children: "children",
        label: "orgName",
      },
      orgName: "",
      userActive: "",
      userInfo: {},
      userList: [],
      // 查询参数
      filterForm: {
        account: "",
        realName: "",
        orgId: "",
        pageNo: 1,
        pageSize: 10,
      },
      totalRows: null,
      ulObj: {
        ul_sty: "width:283px",
      },
    };
  },
  created() {
    // this.nowUserId = store.state.user.userId;
    this.webSocketInit();
    this.getTouristInfo();
  },
  methods: {
    // 获取游客信息
    getTouristInfo(){
      getTouristInfo({pcMac:""}).then(res=>{
        if (res.code == "00000") {
          this.nowUserId = res.data.id
        }
      })
    },
    baseURL() {
      return process.env.VUE_APP_TARGET
    },
    // WebSocket链接
    webSocketInit(){
      // const path=this.baseURL().split("://")[1];
      // 线上
      // const path = "172.31.86.10:21023";
      // var wspath="ws://"+path+"/chat/online/manager/uuid&"+getToken();
      // const path="localhost:9528/";
      const path="localhost:9528";
      const youkeId = "2938-10-11";//标识
      let token = getToken()
      // var wspath="ws://"+path+"/dev-api/business/chat/online/manager/uuid&"+token+"/"+youkeId;
      // 模拟游客登录token为空
      var wspath="ws://"+path+"/dev-api/business/chat/online/manager/uuid&/"+youkeId;
      this.ws = new WebSocket(wspath);
      // console.info("init ws=",this.ws)
      this.ws.onmessage = (e) => {
        console.log("onmessage=",e)
        this.websocketonmessage(e)
      }
      this.ws.onclose = (e) => {
        console.log("onclose=",e)
        this.websocketclose(e);
      };
      this.ws.onopen = (e) => {
        console.log("open=",e)
        this.websocketOpen(e);
      };
    },
    // 链接
    websocketonmessage (e) {
      let res = JSON.parse(e.data);
      const obj = this.sessionList[res.groupId]
      let msgData = {}
      console.log("获取信息=",res)
      switch (res.code) {
        // 消息数据 msgFlag: 0消息， 1通知 
        case "msgData":
          // console.log("this.chatList1=",dateFormat(new Date(res.sendTime), 'yyyy-MM-dd hh:mm:ss'))
          this.chatList.push({
            delFlag: 0,
            msgFlag: 0,
            msg: res.msg,
            sendTime: this.timeStampToTime(new Date(res.sendTime)),
            sendUserName: res.sendUserName,
            sendUserId: res.sendUserId,
            show: false
          })
          this.reduceFlag = 0
          this.sendMessage = ""
          break;
        // 确认数据
        case "ackData":
          if (res.status !== 0) {
            this.$message({
              message: res.tip,
              type: 'warning',
            })
          } else {
            if (res.groupId === this.groupId) {
              let msgData = {
                delFlag: 0,
                msgFlag: 0,
                fileSuffix: res.fileSuffix,
                fileSizeInfo: res.fileSizeInfo,
                fileId: res.fileId,
                infoId: res.infoId,
                msg: res.fileId ? res.msg : this.sendMessage.replace(/</g, '&lt;'),
                sendTime: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
                sendUserName: store.state.user.name,
                sendUserId: store.state.user.userId,
                show: false
              }
              this.chatList.push(msgData)
            }
            this.sendMessage = ''
          }
          break;

        // 已读数据
        case "readData":
          if (this.groupId) {
            this.chatList.forEach(element => {
              element.unreadFlag = 1
            })
          }
          break;
        
        // 撤回数据
        case "delData":
          this.chatList.forEach((child, index) => {
            if (child.infoId === res.infoId) {
              this.chatList[index].delFlag = 1
              this.chatList[index].msgFlag = 1
              this.chatList[index].msg = `${child.sendUserName}撤回了一条消息`
            }
          })
          this.sessionList[res.groupId].lastMsg =  res.tip
          this.sessionList[res.groupId].lastTime = dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
          if (this.sessionList[res.groupId].unreadData > 0) {
           this.sessionList[res.groupId].unreadData--
          }
          
          break;

        // 解散群聊  
        case "groupDelData":
          this.drawerVisible = false
          this.reduceFlag = 1
          if (obj) {
            obj.reduceFlag = 1
            obj.lastMsg = res.tip
          }
          if (res.groupId === this.groupId) {
            msgData = {
              msgFlag: 1,
              msg: res.tip
            }
            this.chatList.push(msgData)
          }
          break;

        // 踢出群聊
        case "reduceData":
          if (res.userIds && (res.userIds[0] === store.state.user.userId)) {
            this.drawerVisible = false
            this.reduceFlag = 1
            
            if (obj) {
              obj.reduceFlag = 1
            }
          }
          this.getMemberList()
          if (obj) {
            obj.lastMsg = res.tip
          }
          if (res.groupId === this.groupId) {
            msgData = {
              msgFlag: 1,
              msg: res.tip
            }
            this.chatList.push(msgData)
          }
          break;

        // 加入群聊
        case "addData":
          if (obj) {
            obj.lastMsg = res.tip
            obj.reduceFlag = 0
          }
          if (res.groupId === this.groupId) {
            this.reduceFlag = 0
            msgData = {
              msgFlag: 1,
              msg: res.tip
            }
            this.chatList.push(msgData)
          }
          
          this.getMemberList()
          break;

        // 修改群名
        case "groupNameData":
          if (res.groupId === this.groupId) {
            this.chatTitle = res.msg
            msgData = {
              msgFlag: 1,
              msg: res.tip
            }
            this.chatList.push(msgData)
            this.groupForm.groupName = res.msg
          }
          if (obj) {
            obj.groupName = res.msg
            obj.lastMsg = res.tip
          }
          break;

        // 消息发送异常
        case "exceptionData":
          break;
        default:
          break
      }
      console.info("chatList",this.chatList)
      this.$nextTick(() => {
        this.scrollBottom(this.groupId)
      })
    },
    // 时间转换
    timeStampToTime(time) {
      var date = time
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? '0' + d : d
      var h = date.getHours()
      h = h < 10 ? '0' + h : h
      var minute = date.getMinutes()
      minute = minute < 10 ? '0' + minute : minute
      var s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + s
    },
    websocketclose(e) {
      // console.log("websocket关闭")
      // code 1000 是主动关闭
      if (e.code !== 1000) {
        this.webSocketInit()
      }
    },
    // 主动关闭
    close () {
      this.ws.close(1000)
    },
    // 连接成功
    websocketOpen(e) {
      console.log("连接成功")
    },
    //数据发送
    websocketsend(agentData, callback) {
      console.log("发送数据=",agentData);
      this.$nextTick(() => {
        this.scrollBottom(this.groupId)
      })
      if (this.ws.readyState === WebSocket.OPEN) {
        //若是ws开启状态
        this.ws.send(JSON.stringify(agentData));
        // 获取游客信息
        this.getTouristInfo();
        this.getChatHistoryPage();
        // 重新获取聊天数据
        // chatHistoryPageApi({ groupName: '' })
        // .then(({ data, code }) => {
        //   if (code === '00000') {
        //     this.sessionList = data
        //     this.getChatHistoryList()
        //     this.sendMessage = ""
        //   }
        // })
      } else {
        this.$message.warning("发送失败")
      }
    },
    // 回车发送
    enterSendBtn (event) {
      if (event.shiftKey && event.keyCode === 13) {
      } else if (event.keyCode === 13) {
        event.preventDefault();
        this.sendBtn()
      }
    },
    // 发送按钮
    sendBtn() {
      const message = this.sendMessage.replace(/\n/g, '').replace(/ /g, '')
      if (!message) return
      this.addSessionList()
    },
    // 左侧对话列表中不存在，即添加
    addSessionList () {
      let sendData = {
        delFlag: 0,
        msgFlag: 0,
        groupId: null,
        msg: this.sendMessage.replace(/</g, '&lt;'),
        code: 'msgData',
        fixedFlag: this.fixedFlag,
        sendUserName: "",
        sendUserId: store.state.user.userId
      }
      this.websocketsend(sendData)
    },
    // 使会话滚动到最底部
    scrollBottom () {
      this.$refs.lastChatItemRef.scrollIntoView()
    },
    // 选择对话
    selectSession (item, index) {
      if (item.unreadData > 0) {
        let sendData = {
          groupId: item.groupId,
          code: 'readData'
        }
        this.websocketsend(sendData)
      }

      this.sessionActive = item.groupId
      this.chatTitle = item.groupName
      this.groupId = item.groupId
      this.fixedFlag = item.fixedFlag
      this.sessionList[item.groupId].unreadData = 0
      this.moreMessageBtnShow = true
      this.groupInfo = item
      this.reduceFlag = item.reduceFlag
      this.getChatHistoryList()
  
      if (item.fixedFlag === 1 && item.reduceFlag === 0) {
        this.groupForm.groupName = item.groupName
        this.getMemberList()
      }
    },
    // 查询聊天记录
    getChatHistoryPage () {
      /** 查询客服信息接入列表 */
      this.loading = true;
      getAccessInfoApi({}).then(response => {
        this.chatList = [];
        console.log("response=",response)
        if (response.code == "00000") {
          if (response.data.length < 10) {
            this.moreMessageBtnShow = false
          }
          response.data.forEach(element=>{
            this.chatList.push({
              infoId:element.infoId,
              delFlag: 0,
              msgFlag: 0,
              msg: element.msg,
              sendTime: element.sendTime,
              sendUserName: element.sendUserName,
              sendUserId: element.sendUserId,
              show: false
            })
          })
        }
        console.log("response=chatList",this.chatList)
        this.loading = false;
      });
    },
    // 查询人员对话种的聊天记录
    getChatHistoryList () {
      chatHistoryListApi({
        groupId: this.groupId
      })
      .then(({ data, code }) => {
        if (code === '00000') {
          this.chatList = data.map(item => ({...item, show: false}))
          if (data.length < 10) {
            this.moreMessageBtnShow = false
          }
          this.$nextTick(() => {
            // document.getElementById("infoId").scrollIntoView(false);
            this.scrollBottom()
          })
        }
      })
    },
    // 鼠标右键
    rightMouse(item, event) {
      item.mouseRightShow = true
      item.rightContainerTop = event.layerY + 5 + 'px'
      item.rightContainerLeft = event.layerX + 5 + 'px'
      this.choseId=item.groupId;
      this.delButton=true;
    },
    //关闭删除按钮
    closeDelButton(){
      this.delButton=false;
      this.choseId='';
    },
    // 删除对话
    delSession (item, index) {
      if (item.groupId === this.groupId) {
        this.groupId = ''
        this.chatTitle = ''
        this.chatList = []
      }
      delete this.sessionList[item.groupId]
      chatHistoryDelApi({
        groupId: item.groupId
      })
    },
    // 查看更多消息
    getMoreMessage () {
      getAccessInfoApi({})
      .then(({ data, code }) => {
        if (code === '00000') {
          if (data.length < 10) {
            this.moreMessageBtnShow = false
          }
          this.chatList = [...data.map(item => ({...item, show: false})), ...this.chatList]
          this.$nextTick(() => {
            const infoId = this.chatList[data.length - 1].infoId
            document.getElementById('infoId-' + infoId).scrollIntoView()
          })
        }
      })
    },
    // 发送表情
    sendEmoji(val) {
      console.log("标签=",val)
      this.sendMessage += val
    },
    // 上传成功回调
    handleAvatarSuccess({ data }) {
      let sendData = {
        groupId: this.groupId,
        msg: data.fileOriginName,
        fileSuffix: data.fileSuffix,
        fileSizeInfo: data.fileSizeInfo,
        fileId: data.fileId,
        code: 'msgData',
        sendUserName: store.state.user.name,
        sendUserId: store.state.user.userId
      }
      this.websocketsend(sendData)

      let obj = this.sessionList[this.groupId]
      if (obj) {
        obj.lastMsg = data.fileOriginName
        obj.lastTime = dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
      } else {
        this.sessionList[this.groupId] = {
          unreadData: 0,
          lastMsg: data.fileOriginName,
          groupId: this.groupId,
          groupName: this.userInfoInPage.realName,
          lastTime: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
        }
        this.sessionActive = this.groupId
      }
    },
    // 上传之前回调
    beforeAvatarUpload(rawFile) {
      if (rawFile.size / 1024 / 1024 > 10) {
        this.$message.error('文件大小不可超过10M!')
        return false
      }
      return true
    },
    // 获取图片
    getIcon (item) {
      return this.baseURL()+`/sysFileInfo/public/preview?fileId=${item.fileId}`
    },
    // 下载按钮
    downloadBtn (item) {
      // window.location.href = this.baseURL()+`sysFileInfo/publicDownload?fileId=${item.fileId}`
      // 本地
      window.location.href = `http://localhost:9528/dev-api/file/sysFileInfo/publicDownload?fileId=${item.fileId}`
    },
    // 撤回按钮
    revokeBtn (item, index) {
      console.log("item=",item)
      revokeAccessInfoApi({ id: item.infoId })
      .then(()=>{
        this.getChatHistoryPage()
      })
    },
    // 撤回按钮
    revokeBtnShowFn (item, index) {
      const time = new Date().getTime() - new Date(item.sendTime).getTime()
      if (time < 1000 * 60 * 2) {
        item.show = true
      }
    },
    // 群组设置按钮 / 查询群组信息
    setGroupBtn() {
      this.drawerVisible = true
    },
    // 设置群组名称
    groupNameBlur () {
      if (!this.groupForm.groupName) {
        this.groupForm.groupName = this.groupInfo.groupName
        return this.$message({
          type: 'warning',
          message: '群组名称不能为空'
        })
      }
      chatGroupEditApi({
        groupId: this.groupId,
        groupName: this.groupForm.groupName
      }).then(({code, data}) => {
        if (code === '00000') {
          this.chatTitle = this.groupForm.groupName
          const obj = this.sessionList[this.groupId]
          obj.groupName = this.groupForm.groupName
        }
      })
    },
    // 解散群组按钮
    dissolveGroupBtn () {
      this.$confirm(
        '确定删除群组?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        chatGroupDelApi({
          groupId: this.groupId,
        }).then(({code, data}) => {
          if (code === '00000') {
            const obj = this.sessionList[this.groupId]
            obj.reduceFlag = 1
            this.reduceFlag = 1
            this.drawerVisible = false
            this.$message({type: 'success',message: '操作成功'})
          }
        })
      })
    },
    // 退出群组按钮
    exitGroupBtn () {
      this.$confirm(
        '确定退出群组?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        chatGroupExitApi({
          groupId: this.groupId,
        }).then(({code, data}) => {
          if (code === '00000') {
            this.reduceFlag = 1
            this.drawerVisible = false
            const obj = this.sessionList[this.groupId]
            if (obj) {
              obj.reduceFlag = 1
            }
            this.$message({type: 'success',message: '操作成功'})
          }
        })
      })
    },
    // 获取成员
    getMemberList () {
      chatGroupInfoApi({
        groupId: this.groupId
      }).then(({code, data}) => {
        if (code === '00000') {
          this.groupUsers = data.groupUsers
          this.adminFlag = data.createUserId === store.state.user.userId
        }
      })
    },
    // 添加成员
    addMember() {
      this.addMemberGroupId = this.groupId;
      this.addBtn();
    },
    // 关闭群聊设置弹窗
    closeDialogQl(){
      // 重置addMemberGroupId为空
      this.addMemberGroupId = ""
    },
    // 删除按钮显示
    delTrue(item){
      this.delUserId=item.userId;
    },
    // 删除按钮隐藏
    delFalse(){
      this.delUserId='';
    },
    //删除按钮判断
    showAvatar(item){
      return this.adminFlag && item.userId !== this.nowUserId && this.delUserId==item.userId
    },
    // 删除成员
    delMember (item, index) {

      this.$confirm(
        '确定删除该成员?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        chatGroupMemberApi({
          addOrReduce: 0,
          groupId: this.groupId,
          groupUserIds: [item.userId]
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.groupUsers.splice(index, 1)
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
        })
      })
    },
    //--弹窗字段信息--------
    filterNode(value, data){
      if(!value){
        return true;
      }
      return data.orgName.indexOf(value) !== -1;
    },
    // 人员树选择
    checkUserList (node, data) {
      console.log("data=",data)
      this.selectedUserList = data.checkedNodes
    },
    // 创建群聊
    addPeopleBtn(){
      this.groupId='';
      this.addBtn();
    },
    addBtn() {
      this.dialogVisible = true
      this.selectedUserList = []
      // 获取人员树
      // getUserTree().then((res) => {
      //   if (res.code === '00000') {
      //     this.treeData = res.data
      //   }
      // })
      getOrgTreeApi().then(({ code, data }) => {
        if (code === '00000') {
          let treeData = this.getNewOrgUserTree(data)
          console.log("treeData=",treeData)
          this.treeData = treeData
        }
      })
    },
    // 处理组织树获取新数据
    getNewOrgUserTree(tree){
      tree.map(async element => {
        // console.log("element=",element)
        let newJson = {}
        if (element.orgParentId === "-1") {
          element.disabled = true
        }
        let orgId = element.orgId;
        if (orgId && element.children) {
          element.children.map(child =>{
            child.disabled = true
          })
          let userList = await this.getUserList(orgId);
          // console.log("userList=",userList)
          // 过滤当前部门之下的数据
          let newUserList = userList.filter(item => item.orgName == element.orgName)
          // console.log("newUserList=",newUserList)
          // 改变数组内容
          let realUserList = newUserList.map(item2 =>({
             ...item2,
            orgName:item2.realName,
            orgId:item2.userId,
            id:item2.userId,
            name:item2.realName,
          }))
          // console.log("realUserList=",realUserList)
          element.children = realUserList.concat(element.children)
          // console.log("element.children=",element.children)
        }
        if(element.children&&element.children.length>0){
          this.getNewOrgUserTree(element.children)
        }
      })
      return tree;
    },
    // 设置部门禁止选择
    setDisabled(data) {
      if (data.nodeType ==='org' || store.state.user.userId === data.id) {
        return true
      }else{
        return false
      } 
    },
    // 创建群聊确定
    confirmBtn () {
      var groupName="";
      var groupUserIds=[]; 
      this.selectedUserList.forEach(item=>{
        if(store.state.user.userId != item.id){
          groupName=groupName+item.name+",";
          groupUserIds.push(item.id);
        }
      });   
      // 添加成员后修改群名称
      // if(this.groupId == ""){
      //   chatGroupMemberApi({
      //     addOrReduce: 1,
      //     groupId: this.groupId,
      //     groupUserIds: groupUserIds
      //   }).then(({ code, data }) => {
      //     if (code === '00000') {
      //       this.$message({
      //         type: 'success',
      //         message: '操作成功'
      //       })
      //       this.dialogVisible = false
      //       if(this.groupForm.groupName.indexOf(",")>-1){
      //         chatGroupEditApi({
      //           groupId: this.groupId,
      //           groupName: this.groupForm.groupName+","+groupName.substring(0,groupName.length-1)
      //         }).then(({code, data}) => {
      //           if (code === '00000') {
      //             this.chatTitle = this.groupForm.groupName
      //             const obj = this.sessionList[this.groupId]
      //             obj.groupName = this.groupForm.groupName
      //           }
      //         })
      //       }
      //     }
      //   })
      //   return ;
      // }
      if (this.addMemberGroupId) {//添加新组员
        if (this.selectedUserList.length < 1){
          this.$message.warning('至少添加1个人');
          return 
        }  
        chatGroupMemberApi({
          addOrReduce: 1,
          groupId: this.addMemberGroupId,
          groupUserIds: this.selectedUserList.map(item => item.id)
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.dialogVisible = false
            // ChatRef.value.getMemberList()
            this.$message.success('操作成功');
            this.getMemberList();
          }
        })
        // 新增群聊
      } else {
        if (this.selectedUserList.length < 2) {
          this.$message.warning('至少添加两个人');
          return ;
        }
        groupName=groupName+store.state.user.name;
        chatGroupAddApi({
          groupName: groupName,
          groupUserIds: groupUserIds
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.dialogVisible = false
            this.isChat = true
            this.newGroupId = data.groupId
          }
        })
      }

    },
    userHandleClose (tag, index) {
      this.selectedUserList.splice(index, 1)
      this.$refs.treeRef.setChecked(tag.userId, false)
    },
    //----组织显示-------------------------------------
    leftShow(val){
      if(val == 1){
        this.isChat=true;
        this.isOrg=false;
      }else{
        this.isChat=false;
        this.isOrg=true;
        this.getOrgTree();
      }
    },
    // 获取部门树
    getOrgTree(){
      // 懒加载
      // getOrgTreeApi({orgId: 0}).then(({ code, data }) => {
      //   if (code === '00000') {
      //     this.orgTree = data
      //     this.selectedOrg = data[0]
      //     this.currentKey = data[0].id
      //     this.$nextTick(() => {
      //       this.$refs.orgTreeRef.setCurrentKey(res.data[0].id)
      //     })
      //   }
      // })
      getOrgTreeApi().then(({ code, data }) => {
        if (code === '00000') {
          this.orgTree = data
        }
      })
    },
    // // 懒加载
    load(tree, resolve) {
      // console.log("tree=",tree)
      let orgid = ''
      if (!tree.data || tree.data.length == 0) {
        orgid = 0
        return
      } else {
        orgid = tree.data.id
      }
      getOrgTreeApi({ orgId: orgid }).then((res) => {
        // console.log("asdhkja=",res)
        const data = res.data.map((item, index) => {
          this.selectedOrg = res.data[0]
          this.currentKey = res.data[0].id
          this.$nextTick(() => {
            this.$refs.orgTreeRef.setCurrentKey(res.data[0].id)
          })
          return item
        })
        resolve(data)
      })
    },
    // 树节点被点击的时候触发	
    async nodeClick (data) {
      console.log("asdjhajkdb=",data)
      // 重置数据
      this.userList = []
      // this.getUserList(data.id)
      let res = await getSysUserPageApi({
        account: '',
        realName: '',
        pageNo: 1,
        pageSize: 100,
        orgId: data.orgId,
        containSelf:false
      })
      // console.log("resujh=",res)
      this.userList = res.data.rows
      this.totalRows = res.data.totalRows

      this.orgName = data.orgName
      this.userActive = ''
      this.userInfo = {}
    },
    // 获取当前组织下的人员
     async getUserList (orgId) {
      let res = await getSysUserPageApi({
        account: '',
        realName: '',
        pageNo: 1,
        pageSize: 100,
        orgId: orgId,
        containSelf:false
      })
      if (res.code === '00000') {
        return res.data.rows
      }
    },
    //查看用户详情
    userClick (item, index) {
      this.userActive = index
      this.userInfo = item
    },
    //发送信息
    sendMessageToUser(userInfo){
      console.log("userInfo=",userInfo)
      chatGroupQueryApi({
        userId: userInfo.userId
      }).then(({ code, data }) => {
        console.log("data=",data)
        if (code === '00000') {
          this.leftShow(1);
          this.chatTitle = userInfo.realName;
          this.groupId = data.groupId;
          this.nowChat = true;
          this.fixedFlag = data.fixedFlag;
          this.getChatHistoryList();
        }
      })
    }
  },
  mounted() {
    this.getChatHistoryPage();
  },

  destroyed() {
    this.close();
  },
  watch: {
    filterText(val) {
      this.$refs.treeRef.filter(val);
    },
    orgFilterText(val) {
      this.$refs.orgTreeRef.filter(val);
    },
    userInfo(val) {
      // console.log("val=",val);
      this.userInfoInPage = val;
      this.chatTitle = val.realName;
    },
    newGroupId() {
      this.getChatHistoryPage();
    },
  },
};
</script>


<style lang="scss" scoped>
p {
  margin: 0;
}
div.chat {
  display: flex;
  height: 100%;
  width: 100%;
  // max-height: 85vh;
  min-height: 85vh;
}
// 右侧对话列表
.chat-container {
  flex: 1;
  height: 100%;
  width: 70%;
  // max-height: 85vh;
  min-height: 85vh;
  background: #f6f8f9;
  .chat-list {
    height: calc(60% - 1px);
    border-bottom: 1px solid #ddd;

    .chat-title {
      height: 40px;
      padding: 10px;
      font-size: 18px;
      font-style: italic;
      border-bottom: 1px solid #ddd;
      align-items: center;
    }
    ul {
      padding: 0px 0px;
      height: calc(72vh - 50px);
      overflow-y: auto;
      .more-message-btn {
        padding-top: 5px;
        text-align: center;
        .el-button {
          font-size: 12px;
          font-style: italic;
        }
      }
      li {
        padding-left: 10px;
        padding-right: 10px;
        list-style-type: none;
      }
      // 我自己的样式
      .myself {
        display: flex;
        justify-content: right;
        & > div:first-child {
          text-align: right;
          padding-right: 10px;
          & > p:first-child {
            font-size: 14px;
            span {
              font-size: 12px;
            }
          }
          p.read-or-not {
            text-align: left;
            margin-top: 5px;
            color: #b0b2b1;
            font-size: 13px;
          }

          & > div {
            display: inline-block;
            position: relative;
          }
          .withdraw-wrapper {
            position: absolute;
            background: #1d2b3f;
            padding: 6px 15px;
            border-radius: 3px;
            left: 50%;
            top: -20px;
            transform: translateX(-50%);
            &::after {
              content: "";
              position: absolute;
              left: 25px;
              bottom: -10px;
              border: 5px solid transparent;
              border-top-color: #1d2b3f;
            }
          }
        }

        & > div:last-child {
          span {
            display: inline-block;
            width: 40px;
            text-align: center;
            line-height: 40px;
            font-size: 20px;
            color: #fff;
            background: #75b9e6;
            border-radius: 50%;
          }
        }
      }

      // 对方的样式
      .others {
        display: flex;
        justify-content: left;

        & > div:first-child {
          span {
            display: inline-block;
            width: 40px;
            text-align: center;
            line-height: 40px;
            font-size: 20px;
            color: #fff;
            background: #5ac994;
            border-radius: 50%;
          }
        }
        & > div:last-child {
          padding-left: 8px;
          p:first-child {
            text-align: left;
            font-size: 14px;

            span {
              font-size: 12px;
            }
          }
        }

        .msg-wrapper {
          background: #ffffff !important;
        }
      }

      // 文件
      .file-wrapper {
        margin-top: 10px;
        ::v-deep .img-file {
          img {
            max-width: 300px;
            max-height: 300px;
            cursor: pointer;
          }
        }
        .other-file {
          display: flex;
          width: 300px;
          border-radius: 5px;
          font-size: 14px;
          border-top-right-radius: 0px;
          background: #fff;
          padding: 5px 10px;
          border: 1px solid #3cbaff;
          div:nth-child(1) {
            position: relative;
            span {
              position: absolute;
              font-size: 14px;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              color: #fff;
            }
          }

          div:nth-child(2) {
            padding: 0px 10px;
            p {
              margin-top: 3px;
              &:first-child {
                text-align: left;
                width: 200px;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
              }
              &:last-child {
                display: flex;
                align-items: center;

                .el-button {
                  margin-left: 20px;
                  padding: 0;
                }
              }
            }
          }
        }
      }

      // 文本信息
      .msg-wrapper {
        margin-top: 8px;
        background: #def4ff;
        padding: 5px 10px;
        width: fit-content;
        max-width: 500px;
        border-radius: 5px;
        font-size: 15px;
        border-top-right-radius: 0px;
        white-space: pre-wrap;
        text-align: left;
      }
    }
  }

  // 消息发送框
  .chat-send {
    height: 160px;
    background: #f6f8f9;
    position: relative;
    // 工具栏
    .chat-tool {
      & > div {
        display: flex;
        align-items: center;
        padding: 5px 20px;
        ::v-deep.el-icon-folder-add {
          font-size: 26px;
          color: #98a0aa;
        }
      }
    }

    // 消息输入框
    .chat-input {
      margin-top: -5px;
      padding: 5px 10px;
      ::v-deep.el-textarea {
        .el-textarea__inner {
          box-shadow: 0 0 0 0px;
          background: transparent;
        }
      }
    }

    .chat-send-btn {
      padding: 5px 9px;
      text-align: right;
    }
  }
}
.avatar {
  background-color: #5ac994;
  font-size: 20px;
  size: 50px;
}
// 左侧个人信息
.my-info {
  width: 39px;
  padding: 20px 0;
  background: #428dbe;
  text-align: center;
  img {
    width: 30px;
  }
  .not-avatar {
    margin-top: 15px;
    cursor: pointer;
  }
}
.ulSpan {
  display: inline-block;
  width: 80px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
</style>
